<template>
  <el-card v-loading="loading">
    <div slot="header">
      {{project.name}}
      <el-button size="small" type="text" @click="$router.push($route.path+ '/edit')" v-if="role <= 1">
        编辑
      </el-button>
    </div>
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1">
        <template slot="title">
          <i class="header-icon el-icon-info"></i> 项目介绍
        </template>
        <el-form label-width="80px">
          <el-form-item label="名称">{{project.name}}</el-form-item>
          <el-form-item label="创建于">{{project.created_at}}</el-form-item>
          <el-form-item label="更新于">{{project.updated_at}}</el-form-item>
          <template v-if="role <= 1">
            <el-form-item label="开始时间">{{project.start_at}}</el-form-item>
            <el-form-item label="结束时间">{{project.end_at}}</el-form-item>
          </template>
          <el-form-item label="直播类型" class="tag-group">
            <template v-for="item in project.platformTypes">
              <el-tag>
                {{item.platform.name + ' - ' + item.type.name}}
              </el-tag>
            </template>
          </el-form-item>
        </el-form>
      </el-collapse-item>


      <el-collapse-item name="2" class="tag-group">
        <template slot="title">
          <i class="fa fa-id-card-o"></i> 项目负责人
        </template>
        <project_search_user placeholder="添加 项目执行人员"
                             @change="addMember"
                             :selected-clear="true"
                             v-if="role === 0"/>
        <el-tag :closable="role === 0" v-for="(u,index) in members" :key="index" @close="removeMember(u)">
          {{u.username}}
        </el-tag>
      </el-collapse-item>

      <el-collapse-item name="3" class="tag-group">
        <template slot="title">
          <i class="fa fa-id-card"></i> 项目执行人员
        </template>
        <project_search_user placeholder="添加 项目负责人"
                             @change="addManager"
                             :selected-clear="true"
                             v-if="$store.state.user.level.id <=2"/>
        <el-tag v-for="(u,index) in managers"
                :closable="$store.state.user.level.id <=2"
                :key="index"
                @close="removeManager(u)">{{u.username}}
        </el-tag>
      </el-collapse-item>

      <!--添加主播记录-->
      <el-collapse-item name="4" v-loading="schedules.loading">
        <template slot="title">
          <i class="fa fa-video-camera"></i> 参与项目的主播
        </template>
        <schedule_list ref="scheduleList" :project="project" mode="project" @add="addSchedule"/>
      </el-collapse-item>

      <!--历史记录-->
      <el-collapse-item name="5" class="tag-group">
        <template slot="title" class="padding">
          <i class="fa fa-clock-o"></i> 曾经参与过该项目的主播
        </template>
        <template v-for="(anchors,name) in historyAnchors">
          <h4>{{name}}</h4>
          <template v-for="item in anchors">
            <el-tag class="pointer"
                    type="success"
                    @click.native="openAnchor(item.anchor)">
              {{item.anchor.name}}
            </el-tag>
          </template>
          <hr/>
        </template>
      </el-collapse-item>

      <el-collapse-item name="6">
        <template slot="title" class="padding">
          <i class="fa fa-area-chart"></i> 查看日报
        </template>
        <calendar v-if="!loading"
                  :date="calendar.list"
                  :loading="calendar.loading"
                  :change="calendarChange"
                  @click="openReport"/>
      </el-collapse-item>
    </el-collapse>
  </el-card>
</template>

<script>
  import _ from 'lodash';

  import Project_search_user from '../component/project_search_user';
  import Project_search_anchor from '../component/project_search_anchor';
  import Calendar from '../component/calendar';
  import Project_add_anchor_schedule from '../component/project_add_anchor_schedule';
  import Schedule_list from '../component/schedules_list';

  export default {
    components: {
      Schedule_list,
      Project_add_anchor_schedule,
      Calendar,
      Project_search_user, Project_search_anchor,
    },
    data() {
      return {
        editable: this.$store.state.user.level.id <= 2,
        activeNames: [],
        loading: true,
        project: {
          id: 0,
          name: '',
          start_at: 0,
          end_at: 0,
          created_at: 0,
          updated_at: 0,
          platformTypes: [],
        },
        role: 3,//当前用户与项目的关系
        managers: [],
        members: [],
        schedules: {loading: false, date: new Date(), list: [], listPage: 1},
        historyAnchors: {},
        calendar: {list: [], loading: true},
        dialogShow: false,
      };
    },
    methods: {
      async fetch() {
        this.loading = true;
        const res = await this.$http.get('/api/project/' + this.$route.params.id);
        if (res instanceof Error)
          return this.$router.replace('/404');

        this.loading = false;
        this.project = {
          id: res.data.id,
          name: res.data.name,
          start_at: moment(res.data.start_at).calendar(),
          end_at: moment(res.data.end_at).calendar(),
          created_at: moment(res.data.created_at).calendar(),
          updated_at: moment(res.data.updated_at).calendar(),
          platformTypes: res.data.platformTypes,
          aggregation: res.data.aggregation,
        };

        this.role = res.data.role;

        if (this.$store.state.user.level.id <= 2 || res.data.role === 0)
          this.role = 0;

        res.data.user.forEach(user => {
          if (user.user_project.type === 0) {
            this.managers.push(user);
          }
          else if (user.user_project.type === 1) {
            this.members.push(user);
          }
        });
        const history = await this.$asyncHttp.get('/api/project/' + this.$route.params.id + '/anchors/history');
        this.historyAnchors = history.data;
      },
      addManager(userId) {
        if (_.find(this.managers, {id: userId}))
          return;
        this.$http.get('/api/project/' + this.project.id + '/add/manager/' + userId).then(res => {
          const member = _.find(this.members, {id: userId});
          if (member)
            this.members.splice(this.members.indexOf(member), 1);
          this.managers.push(res.data);
        }).catch(err => {
          this.$message.error(err.response.data);
        });
      },
      addMember(userId) {
        if (_.find(this.members, {id: userId}))
          return;
        this.$http.get('/api/project/' + this.project.id + '/add/member/' + userId).then(res => {
          const manager = _.find(this.managers, {id: userId});
          if (manager)
            this.managers.splice(this.managers.indexOf(manager), 1);

          this.members.push(res.data);
        }).catch(err => {
          this.$message.error(err.response.data);
        });
      },
      addSchedule(schedule) {
        let anchor = schedule.anchor, platform = anchor.platform;
        if (!this.historyAnchors[platform.name])
          this.historyAnchors[platform.name] = [];
        if (_.findIndex(this.historyAnchors[platform.name], {anchor_id: schedule.anchor_id}) === -1)
          this.historyAnchors[platform.name].push(schedule);
        this.$forceUpdate();
      },
      removeManager(user) {
        this.$confirm(`${user.username} 将不再是负责人`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.$http.get('/api/project/' + this.project.id + '/remove/manager/' + user.id);
          const find = _.find(this.members, {id: user.id});
          this.managers.splice(this.managers.indexOf(find), 1);
          this.$message.success('删除成功!');
        }).catch(() => {
        });
      },
      removeMember(user) {
        this.$confirm(`${user.username} 将不再是执行人员`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.$http.get('/api/project/' + this.project.id + '/remove/member/' + user.id);
          const find = _.find(this.members, {id: user.id});
          this.members.splice(this.members.indexOf(find), 1);
          this.$message.success('删除成功!');
        }).catch(() => {
        });
      },
      openAnchor(anchor) {
        this.$refs['scheduleList'].openWithAnchor(anchor);
        // this.$router.push(`/project/${this.project.id}/anchor/${anchor.id}`);
      },
      openReport(date) {
        this.$router.push(`/project/${this.project.id}/report/${date}`);
      },
      calendarChange(month) {
        console.log('calendarChange', month);
        this.calendar.loading = true;
        this.$http.get(`/api/project/${this.project.id}/calendar/${month}`).then(res => {
          this.calendar.list = res.data;
          this.calendar.loading = false;
        });
      },
      openSchedule(row) {
        this.$router.push({
          name: 'schedule',
          params: {project_id: this.project.id, anchor_id: row.anchor.id, schedule_id: row.id},
        });
      },
    },
    computed: {
      scheduleDateIsToday() {
        return moment(this.schedules.date).diff(moment(), 'day') === 0;
      },
    },
    watch: {
      'schedules.date'(val, oldVal) {
        if (val.getTime() === oldVal.getTime())
          return;
        this.schedules.listPage = 0;
        this.schedules.list = [];
      },
    },
    mounted() {
      this.fetch();
    },
  };
</script>

<style scoped>
  i {
    font-size: 20px;
  }

  .pointer {
    cursor: pointer;
  }
</style>